﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Configuration;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using Com.FoxGlobal.DanielChan.Hyperion.HFMProxy;
using System.Data;


namespace Com.FoxGlobal.Daniel.Midea.TemplateService
{
    /// <summary>
    /// 日记帐Web Service
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class JournalsService : WebServiceBase
    {
        /// <summary>
        /// 初始化 HFM Proxy 
        /// 
        /// TODO Logging模板使用EL5的Logging
        /// 
        /// </summary>
        /// <returns></returns>
        private HFMProxy InitAgent()
        {
            Logging.WriteLog(LoggingLevel.DEBUG, "Init Agent");
            HFMProxy agent = new HFMProxy();
            return agent;
        }

        /// <summary>
        /// 登录　
        /// 
        /// TODO 使用 WF 暴露接口
        /// 
        /// </summary>
        /// <param name="agent"></param>
        private void HFMLogin(HFMProxy agent)
        {
            // TODO 日志使用 EL5.0 接口，级别为 DEBUG
            
            // TODO 将用户相关的信息，抽象到对象中话到Session中进行管理
            agent.Login(this.Session["Cluster"].ToString(), this.Session["Appname"].ToString(), this.Session["Domain"].ToString(),
              this.Session["Username"].ToString(), this.Session["Token"].ToString(), this.Session["Password"].ToString());

        }

        /// <summary>
        /// 退出登录 
        /// </summary>
        /// <param name="agent"></param>
        private void HFMLogout(HFMProxy agent)
        {
            Logging.WriteLog(LoggingLevel.DEBUG, "Logout");
            agent.Logout();
        }

        /// <summary>
        /// 提取日记帐
        /// 
        /// TODO 整合接口
        /// 
        /// </summary>
        /// <param name="agent"></param>
        /// <param name="Session"></param>
        /// <param name="Year"></param>
        /// <param name="Period"></param>
        /// <param name="Scenario"></param>
        /// <param name="Entity"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        private string HFMExtractJournals(HFMProxy agent, String Session, string Year, string Period, string Scenario, string Entity, String Value)
        {
            Logging.WriteLog(LoggingLevel.DEBUG, "HFMExtractJournals(Session={0}, Year={1}, Period={2}, Scenario={3}, Entity={4}, Value={5}, Path={6})", Session, Year, Period, Scenario, Entity, Value, Server.MapPath(String.Format("Data\\{0}\\ExtractJournals.jif", Session)));

            Year = Year.Trim();
            Period = Period.Trim();
            Scenario = Scenario.Trim();
            Entity = Entity.Trim();
            Value = Value.Trim();

            // TODO 目录管理，使用User对象的属性
            string result = agent.ExtractJournals(Year, Period, Scenario, Entity, Value, Server.MapPath(String.Format("Data\\{0}\\ExtractJournals.jif", Session)));

            if (result.Trim().Length > 0)
            {
                throw new WebServiceException(WebServiceErrorCode.Error_Extract_Journals_Failtrue, result);
            }
            else
            {
                result = agent.GetFileContent(Server.MapPath(string.Format("data\\{0}\\ExtractJournals.jif", Session)));
                return result;
            }

        }

        /// <summary>
        /// 加载日记帐
        /// 
        /// TODO 整合接口
        /// 
        /// </summary>
        /// <param name="agent"></param>
        /// <param name="Session"></param>
        /// <param name="journals"></param>
        private void HFMLoadJournals(HFMProxy agent, string Session, string journals)
        {
            Logging.WriteLog(LoggingLevel.DEBUG, "HFMLoadJournals(Session={0}, Journals={1}, Path={2})", Session, journals, Server.MapPath(String.Format("Data\\{0}\\LoadJournals.jif", Session)));

            // TODO 目录管理使用用户的属性
            string result = agent.SetFileContent(Server.MapPath(String.Format("Data\\{0}\\LoadJournals.jif", Session)), journals);
            if (result.Trim().Length > 0)
            {
                throw new WebServiceException(WebServiceErrorCode.Error_Load_Journals_Read_Failture, result);
            }

            result = agent.LoadJournals(Server.MapPath(String.Format("Data\\{0}\\LoadJournals.jif", Session)), Server.MapPath(String.Format("Data\\{0}\\LoadJournals.log", Session)));
            if (result.Trim().Length > 0)
            {
                throw new WebServiceException(WebServiceErrorCode.Error_Load_Journals_Failtrue, result);
            }
        }



        /// <summary>
        /// Description:  获取服务器端的版本号
        /// Calls:            
        /// Called By:     Excel VBA
        /// Parameter:   
        /// Others:         版本号使用  YYYYMMDD 的方式来标识，如 20100707, 20100729等
        /// </summary>
        /// <returns>服务器端版本信息</returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult GetServerVersion()
        {
            return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, ConfigurationManager.AppSettings["Server:Journals:Version"]);
        }


        /// <summary>
        /// Description:  比较服务器与客户端之间的版本是否匹配
        /// Calls:            
        /// Called By:     Excel VBA
        /// Parameter:   strClientVersion         客户端版本
        /// Others:         1、版本号使用  YYYYMMDD 的方式来标识，如 20100707, 20100729等
        ///                     2、服务器版本  > 客户端版本              false
        ///                     3、服务器版本 <= 客户端版本             True
        /// </summary>
        /// <returns>True/false ==>  匹配/不匹配</returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult CheckVersion(Int64 strClientVersion)
        {
            return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, (Int64.Parse(ConfigurationManager.AppSettings["Server:Journals:Version"]) <= strClientVersion).ToString());
        }


        /// <summary>
        /// Description:  获取最新的模板地址
        /// Calls:            
        /// Called By:     Excel VBA
        /// Parameter:   
        /// Others:         1、版本号使用  YYYYMMDD 的方式来标识，如 20100707, 20100729等
        ///                     2、服务器版本  > 客户端版本              false
        ///                     3、服务器版本 <= 客户端版本             True
        /// </summary>
        /// <returns>True/false ==>  匹配/不匹配</returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult GetLastestTemplateURL()
        {
            return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, ConfigurationManager.AppSettings["Server:Journals:LastestTemplateURL"]);
        }


        /// <summary>
        /// Description:  登录HFM
        /// Calls:            
        /// Called By:     Excel VBA
        /// Parameter:   Session
        /// Others:         
        /// </summary>
        /// <returns>True/false ==>  匹配/不匹配</returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult Login(String Session, string cluster, string appname, string domain, string username, string token, string password)
        {

            HFMProxy agent = InitAgent();

            this.Session["Cluster"] = ConfigurationManager.AppSettings["HFM:Cluster"];
            this.Session["Appname"] = appname;
            this.Session["Domain"] = ConfigurationManager.AppSettings["HFM:Domain"];
            this.Session["Username"] = username;
            this.Session["Token"] = ConfigurationManager.AppSettings["HFM:Token"];
            this.Session["Password"] = password;

            try
            {
                HFMLogin(agent);
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, "");
            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, ex.ToString());
            }
        }


        /// <summary>
        /// Description:  退出登录
        /// Calls:            
        /// Called By:     Excel VBA
        /// Parameter:   Session
        /// Others:         
        /// </summary>
        /// <returns>True/false ==>  匹配/不匹配</returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult Logout(String Session)
        {
            this.Session["Username"] = "";

            try
            {
                HFMProxy agent = InitAgent();
                HFMLogout(agent);

                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, "");
            }
            catch (Exception ex)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Logout_Failture, ex.ToString());
            }
        }


        /// <summary>
        /// Description:  获取日记帐
        /// Calls:            
        /// Called By:     Excel VBA
        /// Parameter:   
        /// Others:         1、版本号使用  YYYYMMDD 的方式来标识，如 20100707, 20100729等
        ///                     2、服务器版本  > 客户端版本              false
        ///                     3、服务器版本 <= 客户端版本             True
        /// </summary>
        /// <returns>True/false ==>  匹配/不匹配</returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult ExtractJournals(String Session, string Year, string Period, String Scenario, String Entity, String Value)
        {
            HFMProxy agent = InitAgent();

            // TODO 用户超时放在统一的地方处理
            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                HFMLogin(agent);
                string result = HFMExtractJournals(agent, Session, Year, Period, Scenario, Entity, Value);
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, result);
            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Extract_Journals_Failtrue, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);
            }
        }


        /// <summary>
        /// Description:  提交日记帐
        /// Calls:            
        /// Called By:     Excel VBA
        /// Parameter:   
        /// Others:         1、版本号使用  YYYYMMDD 的方式来标识，如 20100707, 20100729等
        ///                     2、服务器版本  > 客户端版本              false
        ///                     3、服务器版本 <= 客户端版本             True
        /// </summary>
        /// <returns>True/false ==>  匹配/不匹配</returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult LoadJournals(String Session, string sYear, string sPeriod, string sScenario, string journals)
        {
            // TODO 代码重构，变量归整
            HFMProxy agent = InitAgent();
            WebServiceResult wsResult = new WebServiceResult();
            StringBuilder sbr = new StringBuilder();
            ArrayList arr = new ArrayList();
            DateTime DTStar = new DateTime();
            DateTime DTEnd = new DateTime();
            DTStar = DateTime.Now;
            string ErrMsg = string.Empty;

            sYear = sYear.Trim();
            sPeriod = sPeriod.Trim();
            sScenario = sScenario.Trim();


            string ErrMsgFormat = "Journal load started:{0}{1}Journal load ended: {2}. Elapsed time:{3}";

            wsResult.Result = null;

            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                Logging.WriteLog(LoggingLevel.ERROR, "LoadJournals: Session:{0}; Year:{1};Period:{2};Scenrio:{3};Journals:{4}", Session, sYear, sPeriod, sScenario, journals);
                arr = GetFormatJournals(journals);

                if (arr.Count > 0)
                {
                    // TODO 封装成一个方法  是否检查用户提交不具备权限的日记帐
                    // TODO 配置从XML中归整到DB
                    //if (ConfigurationManager.AppSettings["HFM:CheckSecurity"].ToLower() == "true")
                    //{
                    //    wsResult = CheckSecurity(sYear, sPeriod, sScenario, arr);

                    //    //如果有错误信息返回，则返回给客户端
                    //    if (!string.IsNullOrEmpty(wsResult.Result))
                    //    {
                    //        sbr.Append(wsResult.Result.ToString());
                    //        Logging.WriteLog(LoggingLevel.ERROR, "CheckSecurity Result:  {0}", wsResult.Result);
                    //    }
                    //}


                    // TODO 封装成一个方法，是否检查维度组合有效性
                    //if (ConfigurationManager.AppSettings["HFM:CheckDimensionValidate"].ToLower() == "true")
                    //{
                    wsResult = CheckValidateForAccount(sYear, sPeriod, sScenario, arr);
                    Logging.WriteLog(LoggingLevel.ERROR, "CheckValidateForAccount is run({0},{1},{2},Count:{3})", sYear, sPeriod, sScenario, arr.Count.ToString());
                    //返回维度组合检查结果
                    if (!string.IsNullOrEmpty(wsResult.Result))
                    {
                        sbr.Append(wsResult.Result.ToString());
                        Logging.WriteLog(LoggingLevel.ERROR, "CheckValidateForAccount Result:{0}", wsResult.Result);
                    }
                    //}

                    // 判断执行结果的成功失败
                    if (!string.IsNullOrEmpty(sbr.ToString()))
                    {
                        Logging.WriteLog(LoggingLevel.ERROR, "返回错误信息:{0}", sbr.ToString());
                        DTEnd = DateTime.Now;
                        ErrMsg = string.Format(ErrMsgFormat, DTStar.ToString(), sbr.ToString(), DTEnd.ToString(), DateTime.Now.Subtract(DTStar));
                        return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Load_Journals_Failtrue, ErrMsg);
                    }
                }
                else
                {
                    Logging.WriteLog(LoggingLevel.ERROR, "日记账行数:{0}", arr.Count);
                }

                HFMLogin(agent);
                HFMLoadJournals(agent, Session, journals);
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, "");

            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Load_Journals_Failtrue, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);
            }
        }



        /// <summary>
        /// Description:  提取Entity
        /// Calls:            
        /// Called By:     Excel VBA
        /// Parameter:   
        /// Others:         1、版本号使用  YYYYMMDD 的方式来标识，如 20100707, 20100729等
        ///                     2、服务器版本  > 客户端版本              false
        ///                     3、服务器版本 <= 客户端版本             True
        /// </summary>
        /// <returns>True/false ==>  匹配/不匹配</returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult ExtractEntitys(string Session)
        {
            HFMProxy agent = InitAgent();

            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                HFMLogin(agent);
                string result = agent.GetEntities(ConfigurationManager.AppSettings["Journals:Metadata:Language"], ConfigurationManager.AppSettings["HFM:MemberList:Entity"]);
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, result);
            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while ExtractEntitys:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Extract_Dimension_Failture, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);
            }

        }


        /// <summary>
        /// 提取Account
        /// 
        /// TODO 整合导出元数据的接口
        /// 
        /// </summary>
        /// <param name="Session"></param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult ExtractAccounts(string Session)
        {
            HFMProxy agent = InitAgent();

            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                HFMLogin(agent);
                string result = agent.GetAccounts(ConfigurationManager.AppSettings["Journals:Metadata:Language"], ConfigurationManager.AppSettings["HFM:MemberList:Account"]);
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, result);
            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while ExtractAccounts:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Extract_Dimension_Failture, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);
            }
        }



        /// <summary>
        /// 提取ICP
        /// 
        /// TODO 整合ICP到元数据接口
        /// 
        /// </summary>
        /// <param name="Session"></param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult ExtractICPs(string Session)
        {
            HFMProxy agent = InitAgent();

            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                HFMLogin(agent);
                string result = agent.GetICPs(ConfigurationManager.AppSettings["Journals:Metadata:Language"]);
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, result);
            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while ExtractICPs:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Extract_Dimension_Failture, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public List<string> GetClusters()
        {
            return ConfigurationManager.AppSettings["Server:Journals:Clusters:List"].Split(';').ToList();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public List<string> GetApplications()
        {
            return ConfigurationManager.AppSettings["Server:Journals:Applications:List"].Split(';').ToList();
        }


        /// <summary>
        /// 提取Custom1
        /// 
        /// TODO 合并到元数据访问的接口
        /// 
        /// </summary>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult ExtractCustom1()
        {
            HFMProxy agent = InitAgent();
            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                HFMLogin(agent);
                string result = agent.GetCustom1(ConfigurationManager.AppSettings["Journals:Metadata:Language"], ConfigurationManager.AppSettings["HFM:MemberList:Custom1"]);
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, result);
            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while ExtractCustom1:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Extract_Dimension_Failture, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);
            }
        }


        /// <summary>
        /// 提取Custom2
        /// 
        /// TODO 合并到元数据访问的接口
        /// </summary>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult ExtractCustom2()
        {
            HFMProxy agent = InitAgent();
            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                HFMLogin(agent);
                string result = agent.GetCustom2(ConfigurationManager.AppSettings["Journals:Metadata:Language"], ConfigurationManager.AppSettings["HFM:MemberList:Custom2"]);
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, result);
            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while ExtractCustom2:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Extract_Dimension_Failture, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);
            }
        }


        /// <summary>
        /// 提取Custom3
        /// 
        /// TODO 合并到元数据访问的接口
        /// 
        /// </summary>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult ExtractCustom3()
        {
            HFMProxy agent = InitAgent();
            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                HFMLogin(agent);
                string result = agent.GetCustom3(ConfigurationManager.AppSettings["Journals:Metadata:Language"], ConfigurationManager.AppSettings["HFM:MemberList:Custom3"]);
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, result);
            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while ExtractCustom3:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Extract_Dimension_Failture, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);
            }
        }

        /// <summary>
        /// 提取Custom4
        /// 
        /// TODO 合并到元数据访问的接口
        /// 
        /// </summary>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult ExtractCustom4()
        {
            HFMProxy agent = InitAgent();
            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                HFMLogin(agent);
                string result = agent.GetCustom4(ConfigurationManager.AppSettings["Journals:Metadata:Language"], ConfigurationManager.AppSettings["HFM:MemberList:Custom3"]);
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, result);
            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while ExtractCustom4:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Extract_Dimension_Failture, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);
            }
        }


        /// <summary>
        /// 提取维度
        /// 
        /// TODO 合并到元数据访问的接口
        /// 
        /// </summary>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult ExtractDimension(String session, String dimname)
        {
            Logging.WriteLog(LoggingLevel.INFO, "ExtractDimension (session={0}, dimname={1})", session, dimname);

            HFMProxy agent = InitAgent();
            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                HFMLogin(agent);
                string result = agent.GetDimension(ConfigurationManager.AppSettings["Journals:Metadata:Language"], dimname,  ConfigurationManager.AppSettings["HFM:MemberList:" + dimname]);
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, result);
            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while ExtractCustom4:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Extract_Dimension_Failture, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);

                Logging.WriteLog(LoggingLevel.INFO, "--> ExtractDimension (session={0}, dimname={1})", session, dimname);
            }
        }


        
        [WebMethod(EnableSession = true)]
        public WebServiceResult ExtractMetadata(String session)
        {
            Logging.WriteLog(LoggingLevel.INFO, "ExtractDimension (session={0})", session);
            HFMProxy agent = null;
            try
            {
                agent = InitAgent();
                if (this.Session["Username"].ToString().Length <= 0)
                {
                    Logging.WriteLog(LoggingLevel.INFO, "Extract Login");
                    return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
                }


                HFMLogin(agent);

                DataTable Target = new DataTable();

                Target.Merge(agent.GetMetadataWithAll("ACCOUNT", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract Account with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("ENTITY", true));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract Entity with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("SCENARIO", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract SCENARIO with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("YEAR", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract YEAR with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("PERIOD", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract PERIOD with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("VALUE", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract VALUE with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("VIEW", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract VIEW with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("ICP", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract ICP with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("CUSTOM1", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract CUSTOM1 with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("CUSTOM2", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract CUSTOM2 with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("CUSTOM3", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract CUSTOM3 with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("CUSTOM4", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract CUSTOM3 with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("SINGLEENTITY", true));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract SINGLEENTITY with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("BALANCING", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract BALANCING with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("TYPE", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract TYPE with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("JOURNALGROUP", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract JOURNALGROUP with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("LABEL", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract LABEL with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("SECURITYCLASS", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract SECURITYCLASS with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("DEBIT", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract DEBIT with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetMetadataWithAll("CREDIT", false));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract CREDIT with {0} results", Target.Rows.Count);

                StringBuilder sb = new StringBuilder();
                foreach (DataRow row in Target.Rows)
                {
                    sb.Append(row["Dimension"] + ",");
                    sb.Append(row["ID"] + ",");
                    sb.Append(row["ParentID"] + ",");
                    sb.Append(row["Key"] + ",");
                    sb.Append(row["ParentKey"] + ",");
                    sb.Append(row["Path"] + ",");
                    sb.Append(row["Default"] + ",");
                    sb.Append(row["Alias1"] + ",");
                    sb.Append(row["Alias2"] + ",");
                    sb.Append(row["Alias3"] + ",");
                    sb.Append(row["Alias4"] + ",");
                    sb.Append(row["Attr1"] + ",");
                    sb.Append(row["Attr2"] + ",");
                    sb.Append(row["Attr3"] + ",");
                    sb.Append(row["Attr4"]);

                    sb.Append("\r\n");
                }
                Logging.WriteLog(LoggingLevel.INFO, "Extract Metadat:  {0}", sb.Length);
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, sb.ToString());
            }
            catch (WebServiceException ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while ExtractCustom4:  {0}", ex.ToString());
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while ExtractCustom4:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Extract_Dimension_Failture, ex.ToString());
            }
            finally
            {
                Logging.WriteLog(LoggingLevel.INFO, "--> ExtractDimension (session={0})", session);
                if (agent != null) HFMLogout(agent);
            }
        }


        [WebMethod(EnableSession = true)]
        public WebServiceResult ExtractConstraint(String session)
        {
            Logging.WriteLog(LoggingLevel.INFO, "ExtractDimension (session={0})", session);
            HFMProxy agent = null;
            try
            {

                agent = InitAgent();
                if (this.Session["Username"].ToString().Length <= 0)
                {
                    Logging.WriteLog(LoggingLevel.INFO, "Extract Login");
                    return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
                }


                HFMLogin(agent);

                DataTable Target = new DataTable();

                Target.Merge(agent.GetConstraint("ENTITY"));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract Constraint ENTITY with {0} results", Target.Rows.Count);

                Target.Merge(agent.GetConstraint("ACCOUNT"));
                Logging.WriteLog(LoggingLevel.INFO, "After Extract Constraint ACCOUNT with {0} results", Target.Rows.Count);

                StringBuilder sb = new StringBuilder();
                foreach (DataRow row in Target.Rows)
                {
                    sb.Append(row["SourceDimension"] + ",");
                    sb.Append(row["SourceMember"] + ",");
                    sb.Append(row["TargetDimension"] + ",");
                    sb.Append(row["TargetTopMember"] + ",");
                    sb.Append(row["TargetDefault"] );
                    sb.Append("\r\n");
                }
                Logging.WriteLog(LoggingLevel.INFO, "Extract Constraint:  {0}", sb.Length);
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, sb.ToString());
            }
            catch (WebServiceException ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while Constraint:  {0}", ex.ToString());
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while Constraint:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Extract_Dimension_Failture, ex.ToString());
            }
            finally
            {
                Logging.WriteLog(LoggingLevel.INFO, "--> Constraint (session={0})", session);
                if (agent != null) HFMLogout(agent);
            }
        }

        

        /// <summary>
        /// 返回Dimension最新更新时间
        /// 
        /// TODO 返回元数据接口中包含此定义
        /// 
        /// </summary>
        /// <param name="DimensionName"></param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult GetLastUpdate(string DimensionName)
        {
            HFMProxy agent = InitAgent();

            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                HFMLogin(agent);
                string result = string.Empty;

                // TODO 合并到维度获取的部分
                switch (DimensionName.ToLower())
                {
                    case "account":
                        result = agent.GetAccountLastUpdate().ToString();
                        break;
                    case "custom1":
                        result = agent.GetCustom1LastUpdate().ToString();
                        break;
                    case "custom2":
                        result = agent.GetCustom2LastUpdate().ToString();
                        break;
                    case "custom3":
                        result = agent.GetCustom3LastUpdate().ToString();
                        break;
                    default:
                        result = agent.GetAccountLastUpdate().ToString();
                        break;
                }

                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, result);
            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while GetLastUpdate:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Extract_Dimension_Failture, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);
            }
        }


        /// <summary>
        /// 得到Application Name
        /// </summary>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult GetAppName()
        {
            HFMProxy agent = InitAgent();

            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                HFMLogin(agent);
                string result = agent.GetAppName().ToString();
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, result);
            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while GetAppName:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Extract_Dimension_Failture, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);
            }
        }
        
        
        /// <summary>
        /// 检查Dimension是否需要更新
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="AppName"></param>
        /// <param name="LastUpDate"></param>
        /// <param name="Dimension"></param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult CheckDimensionUpdate(string UserName, string AppName, string LastUpDate, string Dimension)
        {
            HFMProxy agent = InitAgent();
            WebServiceResult wsresult = new WebServiceResult();
            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                HFMLogin(agent);
                string result = string.Empty;
                string UName = agent.GetUsername().ToString();
                string AName = agent.GetAppName().ToString();
                wsresult = GetLastUpdate(Dimension);
                //if (UName.Equals(UserName) && AName.Equals(AppName) && Convert.ToDateTime(wsresult.Result) == Convert.ToDateTime(LastUpDate))

                // TODO 这个想干吗?
                if (UName.Equals(UserName) && AName.Equals(AppName) && 1 == 0)
                {
                    result = "true";
                }
                else
                {
                    result = "false";
                }
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, result);
            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while GetAppName:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Extract_Dimension_Failture, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);
            }
        }

        /// <summary>
        /// 提取JournalGroup
        /// </summary>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public WebServiceResult GetJournalGroup()
        {
            HFMProxy agent = InitAgent();
            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                HFMLogin(agent);
                string result = agent.GetJournalGroup();
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, result);
            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while GetJournalGroup:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Extract_Dimension_Failture, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);
            }
        }


        /// <summary>
        /// 检查维度组合的有效性
        /// 
        /// TODO 这个放出来的目的
        /// 
        /// </summary>
        /// <param name="sYear">Year</param>
        /// <param name="sPeriod">Period</param>
        /// <param name="sScenario">Scenario</param>
        /// <param name="Arr">ArrayList泛型格式化日记账</param>
        /// <returns></returns>
        protected WebServiceResult CheckValidateForAccount(string sYear, string sPeriod, string sScenario, ArrayList Arr)
        {
            HFMProxy agent = InitAgent();
            string sValue, sParent, sView, sICP, sAccount, sEntity, sCustom1, sCustom2, sCustom3, sCustom4, result = "", temp, ErrMsg;

            //ArrayList tempArr = new ArrayList();

            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                HFMLogin(agent);

                sParent = ConfigurationManager.AppSettings["HFM:Security:Parent"];
                sValue = ConfigurationManager.AppSettings["HFM:Security:Value"];
                sView = ConfigurationManager.AppSettings["HFM:Security:View"];

                for (int i = 0; i < Arr.Count; i++)
                {
                    // TODO 存储结构解析成数据结构，使用强数据结构传递
                    string[] Dimension = Arr[i].ToString().Split(';');
                    sEntity = Dimension[1];
                    if (sEntity.Contains("."))
                    {
                        sEntity = sEntity.Split('.')[1].ToString();
                    }
                    sAccount = Dimension[2];
                    sICP = Dimension[3];
                    sCustom1 = Dimension[4];
                    sCustom2 = Dimension[5];
                    sCustom3 = Dimension[6];
                    sCustom4 = Dimension[7];
                    //Logging.WriteLog(LoggingLevel.DEBUG, " Validate: Journals:{0}", Arr[i].ToString());
                    
                    // TODO 数据校验
                    temp = agent.Validate(sScenario, sYear, sPeriod, sView, sEntity, sParent, sValue, sAccount, sICP, sCustom1, sCustom2, sCustom3, sCustom4).ToString();
                    Logging.WriteLog(LoggingLevel.DEBUG, " Validate-->GetCell: Scenario:{0};Year:{1};Period:{2};Entity:{3};Account:{4};ICP:{5};C1:{6};C2:{7};C3:{8};C4:{9}-->{10}", sScenario, sYear, sPeriod, sEntity, sAccount, sICP, sCustom1, sCustom2, sCustom3, sCustom4, temp.ToUpper().Contains("CELLSTATUS_INVALID"));
                    if (temp.ToUpper().Contains("CELLSTATUS_INVALID"))
                    {
                        ErrMsg = agent.CheckDimensionValidate(Arr[i].ToString()).ToString();
                        if (!string.IsNullOrEmpty(ErrMsg.Trim()))
                        {
                            result = result + ErrMsg;
                        }
                        //Logging.WriteLog(LoggingLevel.DEBUG, " Validate Account、ICP、C1...: Scenario:{0};Year:{1};Period:{2};Entity:{3}-->ErrorMsg:{4}", sScenario, sYear, sPeriod, sEntity, ErrMsg);
                    }
                }

                // TODO 错误信息的回传，替换错误提示信息
                result = result.Replace("#ICP#", ConfigurationManager.AppSettings["HFM:CheckICPValidateErrMsg"]);
                result = result.Replace("#Custom1#", ConfigurationManager.AppSettings["HFM:CheckCustom1ValidateErrMsg"]);
                result = result.Replace("#Custom2#", ConfigurationManager.AppSettings["HFM:CheckCustom2ValidateErrMsg"]);
                result = result.Replace("#Custom3#", ConfigurationManager.AppSettings["HFM:CheckCustom3ValidateErrMsg"]);

                if (!string.IsNullOrEmpty(result.Trim()))
                {
                    return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, result);
                }
                else
                {
                    return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, "");
                }

            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Error while CheckValidateForAccount:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_ValidateAccount, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);
            }

        }




        /// <summary>
        /// 检查权限
        /// </summary>
        /// <param name="sYear"></param>
        /// <param name="sPeriod"></param>
        /// <param name="sScenario"></param>
        /// <param name="Arr"></param>
        /// <returns></returns>
        protected WebServiceResult CheckSecurity(string sYear, string sPeriod, string sScenario, ArrayList Arr)
        {
            HFMProxy agent = InitAgent();
            string sValue, sParent, sView, sICP, sAccount, sEntity, sCustom1, sCustom2, sCustom3, sCustom4, result = "", temp, ErrMsg;
            int priority;
            if (this.Session["Username"].ToString().Length <= 0)
            {
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_Login_Failture, "用户已经超时，请重新登录!");
            }

            try
            {
                HFMLogin(agent);

                sParent = ConfigurationManager.AppSettings["HFM:Security:Parent"];
                sValue = ConfigurationManager.AppSettings["HFM:Security:Value"];
                sView = ConfigurationManager.AppSettings["HFM:Security:View"];
                sICP = ConfigurationManager.AppSettings["HFM:Security:ICP"];
                sAccount = ConfigurationManager.AppSettings["HFM:Security:Account"];
                sCustom1 = ConfigurationManager.AppSettings["HFM:Security:Custom1"];
                sCustom2 = ConfigurationManager.AppSettings["HFM:Security:Custom2"];
                sCustom3 = ConfigurationManager.AppSettings["HFM:Security:Custom3"];
                sCustom4 = ConfigurationManager.AppSettings["HFM:Security:Custom4"];
                priority = int.Parse(ConfigurationManager.AppSettings["ODS:DATALOCK:MAXREVIEWLEVEL"]);

                for (int i = 0; i < Arr.Count; i++)
                {
                    sEntity = Arr[i].ToString().Split(';')[1];
                    result = result + agent.CheckSecurityResult(sScenario, sYear, sPeriod, sEntity, sParent, sValue, sAccount, sICP, sCustom1, sCustom2, sCustom3, sCustom4, priority, Arr[i].ToString());
                    if (!string.IsNullOrEmpty(result))
                    {
                        Logging.WriteLog(LoggingLevel.ERROR, "CheckSecurity:({0},{1},{2},{3})-->Result:{4}", sScenario, sYear, sPeriod, sEntity, result);
                    }
                    else
                    {
                        Logging.WriteLog(LoggingLevel.ERROR, "CheckSecurity:({0},{1},{2},{3})-->Result:{4}", sScenario, sYear, sPeriod, sEntity, "Pass");
                    }

                }
                //替换错误提示信息
                result = result.Replace("#Permission#", ConfigurationManager.AppSettings["HFM:CheckSecurityErrMsg"]);
                if (!string.IsNullOrEmpty(result.Trim()))
                {
                    return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, result);
                }
                else
                {
                    return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Success, "");
                }

            }
            catch (WebServiceException ex)
            {
                return ex.Result;
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LoggingLevel.ERROR, "Security Check Error:  {0}", ex.ToString());
                return new WebServiceResult(WebServiceModuleCode.Journals, WebServiceErrorCode.Error_ValidateAccount, ex.ToString());
            }
            finally
            {
                HFMLogout(agent);
            }

        }


        /// <summary>
        /// 获取成员ID
        /// </summary>
        /// <param name="lDimID"></param>
        /// <param name="sMemLabel"></param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public string GetMemberID(long lDimID, string sMemLabel)
        {
            HFMProxy agent = InitAgent();
            HFMLogin(agent);
            return agent.GetMemberID(lDimID, sMemLabel).ToString();
        }



        /// <summary>
        ///格式化日记账
        //多体日记账:d;<parent.entity>;<account>;<ICP>;<C1>;<C2>;<C3>;<C4>;<amount type>;<value>
        //单体日记账:s;<entity>;<account>;<ICP>;<C1>;<C2>;<C3>;<C4>;<amount type>;<amount>;<value>
        /// </summary>
        /// <param name="Journals"></param>
        /// <returns>ArrayList</returns>
        protected ArrayList GetFormatJournals(string Journals)
        {
            //日记账实体
            ArrayList Arr = new ArrayList();

            string[] sArray = Regex.Split(Journals, @"\\n\\n", RegexOptions.IgnoreCase);

            //按\n\n分隔数据
            for (int i = 0; i < sArray.Length; i++)
            {

                try
                {
                    //将单体和多体日记账保存到同一个ArrayList中，单体日记账以s开头标记，多体以d开头标记
                    if (sArray[i].ToString().Contains("!JOURNAL="))
                    {
                        //string[] temps = Regex.Split(sArray[i].ToString(), @"\\n", RegexOptions.IgnoreCase);
                        ArrayList temps = new ArrayList(Regex.Split(sArray[i].ToString(), @"\\n", RegexOptions.IgnoreCase));
                        for (int k = 0; k < temps.Count; k++)
                        {
                            //移除空行
                            if (string.IsNullOrEmpty(temps[k].ToString().Trim()))
                            {
                                temps.RemoveAt(k);
                            }
                        }

                        //多实体
                        if (temps[0].ToString().Contains("!JOURNAL=") && temps[0].ToString().Substring(temps[0].ToString().Length - 2, 2) == ";;")                       
                        {
                            for (int j = 2; j < temps.Count; j++)
                            {
                                string temp2 = "d;";
                                string value = temps[0].ToString().Split(';')[4].ToString() + ";";
                                if (!string.IsNullOrEmpty(temps[j].ToString()))
                                {
                                    Arr.Add(temp2 + temps[j] + value);
                                }
                            }
                        }//单实体
                        else if (temps[0].ToString().Contains("!JOURNAL="))
                        {
                            string temp2 = "s;" + temps[0].ToString().Split(';')[7].ToString() + ";";
                            string value = temps[0].ToString().Split(';')[4].ToString() + ";";
                            for (int j = 2; j < temps.Count; j++)
                            {
                                if (!string.IsNullOrEmpty(temps[j].ToString()))
                                {
                                    Arr.Add(temp2 + temps[j] + value);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logging.WriteLog(LoggingLevel.ERROR, "GetFormatJournals Error: {0};Journal:{1}", ex.ToString(), sArray[i].ToString());
                }
            }

            return Arr;
        }

        [WebMethod(EnableSession = true)]
        public ComplexWebServiceResult GetComplexResult()
        {
            return new ComplexWebServiceResult();
        }

    }
}
